<template>
    <div class="checkbox-group">
      <slot />
    </div>
</template>

<script>
  export default {
    /*
    * 不能绑定相同引用类型值。
    * */
    name: 'Checkgroup',
    model: {
      prop: 'checkArr',
      event: 'check-group'
    },
    props: {
      checkArr: {
        type: Array,
        default () {
          return []
        }
      }
    },
    provide () {
      return {
        test: this.checkArr
      }
    },
    beforeMount() {
      let _this = this
      this.$on('check-item-update', function () {
        let idx
        let hasFalse = false
        _this.$children.forEach((i,n)=>{
          if(i._name === '<CartHeader>') {
            idx = n
          }else{
            if(i.cartItemChecker === false) {
              hasFalse = true
            }
          }
        })
        _this.$children[idx].checkAllTogger(!hasFalse)
      })
    },
    mounted () {
      let idx
      const hasHeader = this.$children.some((i, n) => {
        idx = n
        return i._name === '<CheckgroupHeader>'
      })
      if (hasHeader) {
        this.$children[idx].checkAllTogger(this.checkArr.length === (this.$children.length - 1))
      } else {
        this.$children[idx].checkAllTogger(this.checkArr.length === this.$children.length)
      }
    },
    created () {
      const _this = this
      this.$on('click-checkbox-group-item', function (x) {
        const Arr = this.checkArr
        function setModelData () {
          let idx
          const ok = Arr.some((i, n) => {
            idx = n
            return i === x
          })
          if (ok) {
            Arr.splice(idx, 1)
          } else {
            Arr.push(x)
          }
        }
        setModelData()
        this.$emit('check-group', Arr)
      })

      this.$on('click-toggle-all', function () {
        this.toggleAll()
      })
    },
    methods: {
      checkAll () {
        this.$children.forEach((i) => {
          if (i._name === '<CheckgroupItem>' && !i.cartItemChecker) {
            i.onCheck()
          }
        })
      },
      cleanAll () {
        this.$children.forEach((i) => {
          if (i._name === '<CheckgroupItem>' && i.cartItemChecker) {
            i.onCheck()
          }
        })
      },
      toggleAll () {
        const cartItemArr = []
        this.$children.forEach((i) => {
          if (i._name === '<CheckgroupItem>') {
            cartItemArr.push(i._name)
          }
        })
        if (this.checkArr.length === cartItemArr.length) {
          this.cleanAll()
        } else {
          this.checkAll()
        }
      }
    }
  }
</script>

<style scoped>

</style>
